<!-- 设备使用时间 -->
<template>
  <div>
    <div class="searchbox">
      <el-form :inline="true" size="small" label-width="100px">

        <el-form-item label="设备">
          <!-- <el-input size="small" v-model="form.device" placeholder="设备"></el-input> -->
          <el-select v-model="form.device" multiple placeholder="请选择">
            <el-option v-for="item in deviceList" :key="item.id" :label="item.codeAndName" :value="item.id">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker v-model="form.fromDate" type="date" format="yyyy-MM-dd" placeholder=""></el-date-picker>
        </el-form-item>
        <el-form-item label="至" label-width="25px">
          <el-date-picker v-model="form.toDate" type="date" format="yyyy-MM-dd" placeholder=""></el-date-picker>
        </el-form-item>
        <el-form-item style="margin-left: 20px;">
          <el-button size="mini" @click='loadData' type="primary">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" @click="clenaFrom">清除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="contentbox">
      <equipment-data-infomation :detailData='usingData' :deviceId='this.form'></equipment-data-infomation>
      <div id='my-chart-1' style='width：200px;height:300px'></div>
      <using-data-infomation :summaryData='summaryData'></using-data-infomation>
      <div id='my-chart-2' style='width：200px;height:300px'></div>
    </div>
  </div>
</template>

<script>
  import {
    getEquipmentUtilization,
    getAllDevice
  } from "service/task";

  import {
    getAll
  } from 'utils/common';
  import JtEasyCollapse from 'components/jt-easy-collapse/index';
  import echarts from 'echarts';
  import EDataInfo from 'dialog/report-center/equipment-utilization-ratio/equipment-data-infomation';
  import UDataInfo from 'dialog/report-center/equipment-utilization-ratio/using-data-infomation';
  export default {
    name: 'RemindingCenter',
    components: {
      'jt-easy-collapse': JtEasyCollapse,
      'equipment-data-infomation': EDataInfo,
      'using-data-infomation': UDataInfo,
    },
    data() {
      return {
        lineChart: {},
        barChart: {},
        form: {
          device: "",
          fromDate: "",
          toDate: ""
        },
        deviceList: [],
        testList: [],
        usingData: {},
        summaryData: [],
      }
    },
    mounted() {
      getAllDevice().then(res => {
        this.deviceList = res.data.result;
      });
      // this.showList();
      this.drawLine();
    },
    methods: {
      loadData() {
        this.showList();
      },
      getSingleData(deviceId, date) {
        for (let i = 0; i < this.testList.length; i++) {
          let data = this.testList[i];
          if (data.operate_time == date && data.device_id == deviceId) {
            return data;
          }
        }
        return {
          occupy: 0,
          cnt: 0,
          work_time: 0
        };
      },
      getDeviceIdData(deviceId) {
        var  y = 0;
        for (let i = 0; i < this.testList.length; i++) {
          let data = this.testList[i];
          if (data.device_id == deviceId) {
            y=y+1;
          }
          return y;
        }
      },
      getDeviceName(deviceId) {
        for (let i = 0; i < this.deviceList.length; i++) {
          if (this.deviceList[i].id == deviceId) {
            return this.deviceList[i].codeAndName;
          }
        }

      },
      drawLine() {
        // 基于准备好的dom，初始化echarts实例
        let myChart1 = echarts.init(document.getElementById('my-chart-1'))
        // 绘制图表
        myChart1.setOption({
          title: {
            // text: '设备使用时间(分钟)'
            text: '设备利用率（%）'
          },
          tooltip: {},
          xAxis: {
            type: 'category',
            data: ['1', '2', '3', '4', '5', '6', '7']
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            type: 'line'
          }]
        });
        this.lineChart = myChart1;
        // 基于准备好的dom，初始化echarts实例
        let myChart2 = echarts.init(document.getElementById('my-chart-2'))
        // 绘制图表
        myChart2.setOption({
          title: {
            // text: '设备使用总时间（分钟）'
            text: '设备平均利用率（%）'
          },
          tooltip: {},
          xAxis: {
            type: 'category',
            data: ['1', '2', '3', '4', '5', '6', '7']
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            type: 'bar'
          }]
        });
        this.barChart = myChart2;
      },
      clenaFrom() {
        // this.form.fromDate = "";
        // this.form.toDate = "";
        // // this.form.device="";

        this.form = {
          device: [],
          fromDate: "",
          toDate: ""
        };
        // this.$router.go(0)
      },
      // 表格数据展示
      showList() {
        if (!this.form.device || !this.form.fromDate || !this.form.toDate ||
          this.form.device.length <= 0 || this.form.fromDate == '' || this.form.toDate == '') {
          this.$message({
            type: 'error',
            message: '请选择设备和起止时间!'
          });
          return;
        }
        /**
         * 清空画布
         */
        this.lineChart.clear();
        this.lineChart.showLoading();
        this.barChart.showLoading();
        getEquipmentUtilization({
          // this.axios.get('/system/testFieldList', {
          deviceId: this.form.device.join(','),
          fromDate: this.form.fromDate,
          toDate: this.form.toDate
        }).then(res => {
          this.testList = res.data.result.list;
          this.summaryData = [];
          let that = this;

          let lineX = getAll(this.form.fromDate, this.form.toDate);

          this.usingData.dateList = lineX;

          let usingDataList = [];
          this.usingData.usingList = usingDataList;

          this.summaryData.fromDate = this.form.fromDate.format();
          this.summaryData.toDate = this.form.toDate.format();

          let barX = [];
          let barY = [];

          let deviceArr = this.form.device;

          let dataSeries = [];

          let barData=[];

          
          deviceArr.forEach(deviceId => {
            let summaryData = [];
            let deviceData = {};
            deviceData.type = 'line';
            deviceData.name = that.getDeviceName(deviceId);
            deviceData.data = [];

            summaryData.name = deviceData.name;
            summaryData.deviceId = deviceId;

            let usingData = {};
            usingData.name = deviceData.name;


            let totalUsed = 0,
              total = 0,
              totalCnt = 0;

            barX.push(deviceData.name);

            let singleBar={};
            singleBar.name=deviceData.name;


            let dayCnt = 0;

            lineX.forEach(date => {
              let singleData = that.getSingleData(deviceId, date);

              // deviceData.data.push(singleData.occupy ? singleData.occupy : 0);
              deviceData.data.push( singleData.work_time == 0 ? 0 : (singleData.occupy*100 / singleData.work_time).toFixed(2));
              totalUsed += singleData.occupy;
              totalCnt += singleData.cnt;
              total += singleData.work_time;

              // usingData[date] = singleData.occupy ;
              usingData[date] = singleData.work_time == 0 ? 0 : (singleData.occupy*100 / singleData.work_time).toFixed(2);
              dayCnt++;
            })
            dataSeries.push(deviceData);

            // barY.push(totalUsed);
            barY.push(total == 0 ? 0 : (totalUsed * 100 / total).toFixed(2));
           
            singleBar.data=[totalUsed];
            singleBar.type='bar';
            singleBar.itemStyle={
							normal: {
								label: {
									show: true, //开启显示
									position: 'top', //在上方显示
									textStyle: { //数值样式
										color: 'black',
										fontSize: 16
									}
								}
							}
						};


            barData.push(singleBar);

            summaryData.occupy = totalUsed;
            // summaryData.workTime = total;
            // var t = that.getDeviceIdData(deviceId);
            var  y = 0;
            for (let i = 0; i < this.testList.length; i++) {
              let data = this.testList[i];
              if (data.device_id == deviceId) {
                y=y+1;
              }
            }
            summaryData.workTime = total*lineX.length/y;
            summaryData.cnt = totalCnt;
            // summaryData.rate = (totalUsed/dayCnt).toFixed(2);
            // summaryData.rate = (total == 0 ? 0 : (totalUsed * 100 / total).toFixed(2));
            summaryData.rate = (summaryData.workTime == 0 ? 0 : (totalUsed * 100 / summaryData.workTime).toFixed(2));
            // usingData.rate = summaryData.rate;
            // usingData.rate = (summaryData.rate*this.testList.length/this.usingData.dateList.length).toFixed(2);
            usingData.rate =summaryData.rate;
            usingDataList.push(usingData);


            that.summaryData.push(summaryData);
          })
          var xData = [];
          var yData = [];
          for(var i =0; i < that.summaryData.length; i++) {
              xData[i] = this.summaryData[i]['name'].substring(0,7);
              yData[i] = this.summaryData[i]['rate'];
          }
          this.lineChart.setOption({
            title: {
              // text: '设备使用时间(分钟)'
              text: '设备利用率（%）'
            },
            tooltip: {},
            xAxis: {
              type: 'category',
              data: lineX
            },
            yAxis: {
              type: 'value'
            },
            legend:{ 
              "icon": "circle",
                // "itemGap": 15,
                // 'itemWidth':10,
                "right": "30%",
                "left":"12%",
                data:barX
            },
            series: dataSeries
          })
          debugger;
          this.barChart.setOption({
            xAxis: {
              type: 'category',
              // data: ['使用统计']
              data: xData
            },
            color:['#4169E1'],
            yAxis: {},
            series:[{ 
              data: yData,
              type: 'bar',
              barWidth : 50,
              itemStyle: {
                normal: {
                  label: {
                    show: true, //开启显示
                    position: 'top', //在上方显示
                    textStyle: { //数值样式
                      color: 'black',
                      fontSize: 16
                    }
                  }
                }
              },
            }]
          })


          this.lineChart.hideLoading();
          this.barChart.hideLoading();
        });
      },
    }
  }
</script>
